import { Controller, Get, Header, Query, Res, Sse } from '@nestjs/common';
import { OpenaiService } from './openai.service';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';

/**
 * 前端测试
 * cd /public
 * http-server -c-1 -p 8081 -o ./sse-client.html
 */
@Controller('openai')
export class OpenaiController {
  private apiKey: string | undefined;
  constructor(
    private readonly openaiService: OpenaiService,
    config: ConfigService,
  ) {
    this.apiKey = config.get('DASHSCOPE_API_KEY');
  }

  @Sse('question-sse')
  question(@Query('query') query: string): Promise<Observable<any>> {
    return this.openaiService.question(this.apiKey, query);
  }

  // 手动实现 SSE 协议
  @Get('question-stream')
  @Header('Content-Type', 'text/event-stream')
  @Header('Cache-Control', 'no-cache')
  @Header('Connection', 'keep-alive')
  createChat(@Query('query') query: string, @Res() res) {
    let count = 0;
    const intervalId = setInterval(() => {
      if (count >= 10) {
        res.write('event: end\ndata: 流结束\n\n');
        res.end();
        clearInterval(intervalId);
        return;
      }

      // SSE 格式
      res.write(
        Buffer.from(
          `data: 消息 ${count} - ${new Date().toISOString()} - ${query}\n\n`,
          'utf8',
        ).toString('utf8'),
      );
      count++;
    }, 1000);

    // 客户端断开连接时清理
    res.on('close', () => {
      clearInterval(intervalId);
    });
  }
}
